import Storage from '@/common/Storage'
import { modal } from '@/common/fun'

import { objTranslate } from '@/common/helper'
import { getSystemConf } from '@/api/system'

const state = {
  ischeck: false,
  commonConfig: false,
  tabbarCurrentIndex: 0,
  tabTags: [0, 0]
}

const mutations = {
  SET_CURRENT_TABBAR (state, idx) {
    state.tabbarCurrentIndex = idx
  },
  SET_TABBAR_TAG (state, { idx, num }) {
    // state.tabTags[idx] = num
    const tempTags = objTranslate(state.tabTags)
    console.log(tempTags)
    tempTags[idx] = num
    state.tabTags = objTranslate(tempTags)
  },
  SET_COMMON_CONFIG (state, value) {
    state.commonConfig = value
    Storage.set('commonConfig', value, 1)
  },
  SET_CHECK_STATUS: (state, value) => {
    state.ischeck = value
    Storage.set('ischeck', value, 1)
  }
}

const actions = {
  tabbarTagAdd: ({ state, commit }, { idx, num = 1 }) => {
    console.log(idx, num)
    const tempNum = state.tabTags[idx]
    const newNum = tempNum + num // 可以正负
    if (newNum < 0) throw Error('数据不能为负')
    commit('SET_TABBAR_TAG', { idx, num: newNum })
  },
  tabbarTagClear: ({ state, commit }, { idx }) => {
    commit('SET_TABBAR_TAG', { idx, num: 0 })
  },
  setTabActiveIdx: ({ commit }, value) => {
    commit('SET_CURRENT_TABBAR', value)
  },
  // async 相当于 隐式的promise
  async loadCommonConfig ({ commit, state }, opts = {}) {
    try {
      const { isOnline = false } = opts
      let commonConfig = state.commonConfig || Storage.get('commonConfig')
      if (isOnline || !commonConfig || JSON.stringify(commonConfig) === '{}') {
        commonConfig = await getSystemConf().then(res => res.data).catch(({ msg = '' }) => { throw Error(msg || '获取全局配置失败') })
      }
      commit('SET_COMMON_CONFIG', commonConfig)
      return commonConfig
    } catch (e) {
      modal(e.message)
    } finally {

    }
  }
}

const getters = {
  getTabbarTags: (state) => () => {
    return state.tabTags
  },
  tabbarCurrentIndex: (state) => state.tabbarCurrentIndex ? state.tabbarCurrentIndex : 0,
  commonConfig: (state) => state.commonConfig || Storage.get('commonConfig'),
  getIsCHeck: (state) => state.ischeck || Storage.get('ischeck')
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
